<template>
  <div>
    <r-search :searchForm="searchForm" :searchHandle="searchHandle" :searchData="searchData" />
    <r-search :searchHandle="searchHandleAdd" />
    <div>
      <el-dialog width="35%" title="运维人员绑定站点" :visible.sync="dialogFormVisible">
        <el-form style="display: flex;justify-content: center;">
          <el-form-item label="运维员" :label-width="formLabelWidth">
            <el-select placeholder="请选择运维员" :clearable="true" v-model="agentValue" style="width:15.42rem">
              <el-option v-for="item in agentArr" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <el-form style="display: flex;justify-content: center;">
          <el-form-item label="换电套餐" :label-width="formLabelWidth">
            <el-select placeholder="请选择换电套餐" :clearable="true" v-model="agentIdValue" multiple style="width:15.42rem">
              <el-option v-for="item in agentIdArr" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="affirmAgentFn">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <r-table :isSelection="false" :isIndex="false" :isPagination="true" :tableData="tableData" :tableCols="tableCols"
      :tablePage="tablePage" @refresh="init()"></r-table>
    <r-form :formRules="formRules" :formHandle="formHandle" :formData="formData" :formCols="formCols" ref="elForm"
      labelWidth="200px" dialogWidth="700px" :isHandle="true" />
    <r-form :formRules="formRulesEditPsw" :formHandle="formHandleEditPsw" :formData="formDataEditPsw"
      :formCols="formColsEditPsw" ref="elFormEditPsw" labelWidth="200px" dialogWidth="1000px" :isHandle="true" />
    <r-form :formRules="formRulesActive" :formHandle="formHandleActive" :formData="formDataActive"
      :formCols="formColsActive" ref="elFormActive" labelWidth="200px" dialogWidth="1000px" :isHandle="true" />

    <Affiliated_agents v-if="Affiliated_agents_data.show" v-on:Affiliated_agents_call="Affiliated_agents_call">
    </Affiliated_agents>

    <Operation_record ref="Operation_record"></Operation_record>
  </div>
</template>
<script>
  import Affiliated_agents from "./cus/Affiliated_agents";
  import Operation_record from "./cus/Operation_record";
  export default {
    components: {
      Affiliated_agents,
      Operation_record
    },
    data() {
      var checkpass = (rule, value, callback) => {
        if (value != this.formData.password) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      };
      var checkpass2 = (rule, value, callback) => {
        if (value != this.formDataEditPsw.password) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      };
      return {
        Affiliated_agents_data: {
          show: false
        },
        searchData: {
          userName: "",
          phone: "",
          status: ""
        },
        searchForm: [
          {
            type: "input",
            prop: "userName",
            placeholder: "维护人名称",
            width: 180
          },
          {
            type: "input",
            prop: "phone",
            placeholder: "手机号",
            width: 150
          },
          {
            type: "date",
            prop: "phone",
            placeholder: "更新时间",
            width: 250
          },
          {
            type: "select",
            prop: "status",
            placeholder: "启用状态",
            width: 150,
            options: [
              {
                label: "正常",
                value: "1"
              },
              {
                label: "禁用",
                value: "2"
              }
            ]
          }
        ],
        searchHandleAdd: [
          {
            label: "新增运维人员",
            type: "success",
            handle: e => this.elFormVisible()
          },
          {
            label: "运维绑定站点",
            type: "success",
            handle: e => {
              this.dialogFormVisible = true;
            }
          }
        ],
        searchHandle: [
          {
            label: "搜索",
            type: "success",
            icon: "el-icon-search",
            handle: e => this.init()
          }
          // {
          //     label: '重置',
          //     icon: 'el-icon-refresh-right',
          //     handle: e => this.searchFromReset()
          // }
        ],
        tableData: [],
        tableCols: [
          {
            label: "序号",
            prop: "id"
          },
          {
            label: "手机号",
            prop: "phone"
          },
          {
            label: "名称",
            prop: "userName"
          },
          {
            label: "授权信息",
            prop: "openId"
          },
          {
            label: "所属运营商",
            prop: "operatorName"
          },
          {
            label: "换电柜数量",
            prop: "excNum"
          },
          {
            label: "充电柜数量",
            prop: "chrNum"
          },
          {
            label: "更新时间",
            prop: "ctime"
          },
          {
            label: "启用状态",
            prop: "status",
            values: [1, 2],
            type: "switch",
            change: async row => {
              const res = await this.apis.maintenancer_updata({
                id: row.id,
                status: row.status
              });

              this.$message({
                message: "操作成功！",
                type: "success"
              });
            }
          },
          {
            label: "操作",
            type: "button",
            width: 400,
            btnList: [
              {
                label: "操作记录",
                type: "text",
                handle: row => {
                  this.$refs.Operation_record.showFun(row);
                }
              },
              // {
              //   label: '查看已关联代理商',
              //   type: 'text',
              //   handle: (row) => {
              //     this.Affiliated_agents_data.show=true;
              //   }
              // },
              {
                label: "编辑",
                type: "text",
                handle: row => this.elFormDetail(row)
              },
              {
                label: "删除",
                type: "text",
                handle: row => {
                  this.$confirm("确定要删除吗?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                  })
                    .then(async () => {
                      var res = await this.apis.maintenancer_del({
                        id: row.id
                      });
                      this.$message({
                        type: "success",
                        message: "删除成功!"
                      });
                      this.init();
                    })
                    .catch(() => { });
                }
              }
            ]
          }
        ],
        tablePage: { limit: 10, page: 1, total: 0 },
        formData: {
          userName: "",
          phone: ""
        },
        formCols: [
          {
            type: "input",
            label: "运维人员名称",
            placeholder: "请输入运维人员名称",
            width: 350,
            prop: "userName"
          },
          {
            type: "input",
            label: "手机号码",
            placeholder: "请输入运维人员名称",
            width: 350,
            prop: "phone"
          }
          // { type: "select", label: "选择用户", placeholder: '', width: 350, prop: "phone", },
        ],
        formRules: {
          userName: [{ required: true, message: "请输入", trigger: "blur" }],
          phone: [{ required: true, message: "请输入", trigger: "blur" }]
          // account: [{ required: true, message: '账号', trigger: 'blur' },],
          // password: [{ required: true, message: '密码', trigger: 'blur' }],
          // enterPassword: [
          //     { required: true, validator: checkpass, message: '两次输入密码不一致', trigger: 'blur' },
          // ],
          // remark: [
          //     { required: true, message: '备注', trigger: 'blur' },
          // ],
        },
        formHandle: [
          {
            label: "取消",
            handle: e => this.elFormVisible()
          },
          {
            label: "确定",
            type: "success",
            handle: e => this.elFormSubmit()
          }
        ],
        //密码
        formDataEditPsw: {
          password: "",
          enterPassword: ""
        },
        formColsEditPsw: [
          {
            type: "input",
            inputType: "password",
            label: " 密码",
            placeholder: "请输入密码",
            width: 350,
            prop: "password"
          },
          {
            type: "input",
            inputType: "password",
            label: "确认密码",
            placeholder: "请输入确认密码",
            width: 350,
            prop: "enterPassword"
          }
        ],
        formRulesEditPsw: {
          password: [{ required: true, message: "密码", trigger: "blur" }],
          enterPassword: [
            {
              required: true,
              message: "请输入",
              trigger: "blur"
            },
            { validator: checkpass2 }
          ]
        },
        formHandleEditPsw: [
          {
            label: "取消",
            handle: e => this.elFormVisibleEditPsw()
          },
          {
            label: "确定",
            type: "success",
            handle: e => this.elFormSubmitEditPsw()
          }
        ],
        //禁用恢复
        formDataActive: {
          // id: "",
        },
        formColsActive: [
          { label: "是否恢复/禁用选定账号", width: 350, prop: "" }
          // { type: "input", label: "确认密码", placeholder: '请输入确认密码', width: 350, prop: "enterPassword" },
        ],
        formRulesActive: {
          // name: [{ required: true, message: '运维人员名称', trigger: 'blur' },],
        },
        formHandleActive: [
          {
            label: "取消",
            handle: e => this.elFormVisibleActive()
          },
          {
            label: "确定",
            type: "primary",
            handle: e => this.elFormSubmitActive()
          }
        ],
        agentArr: [],
        agentIdArr: [],
        dialogFormVisible: false,
        formLabelWidth: "80px",
        agentValue: "",
        agentIdValue: []
      };
    },

    watch: {
      dialogFormVisible: {
        handler(newValue, oldValue) {
          if (!newValue && oldValue) {
            this.agentValue = "";
            this.agentIdValue = [];
            this.operationFn();
          } else if (newValue && !oldValue) {
            this.agentValue = "";
            this.agentIdValue = [];
            this.operationFn();
          }
        },
        deep: true // 深度监听
      },
      agentValue: {
        handler(newValue) {
          // console.log('新', newValue, '---旧', oldValue)
          if (newValue) {
            this.inquireAgentFn(newValue);
          } else {
            this.inquireAgentFn("");
          }
        },
        deep: true // 深度监听
      }
    },
    mounted() {
      this.init();
      this.site_list();
    },
    methods: {
      Affiliated_agents_call() {
        this.Affiliated_agents_data.show = false;
      },
      async init() {
        this.tablePage.offset = this.tablePage.page;
        let param = {
          ...this.searchData,
          ...{
            pageNum: this.tablePage.page,
            pageSize: this.tablePage.limit,
            phone: this.searchData.phone,
            userName: this.searchData.userName,
            status: this.searchData.status
          }
        };
        // console.log(param);
        let res = await this.apis.maintenancer_list(param);
        if (res) {
          this.tablePage.total = res.total;
          this.tableData = res.rows || [];
        }
      },
      //站点列表
      async site_list() {
        const res = await this.apis.site_list({
          pageNum: 1,
          pageSize: 1000
        });
        this.agentIdArr = [];
        const list = res.rows || [];
        console.log(222, res.rows);
        if (list.length !== 0) {
          list.forEach(i => {
            let testAgentArr = {
              id: i.id,
              name: i.name
            };
            this.agentIdArr.push(testAgentArr);
          });
        }
      },

      // 通过运维人员的id查询他已经绑定了那几个设备
      async inquireAgentFn(id) {
        const res = await this.apis.maintenancerSiteList(id);
        this.agentIdValue = [];
        const list = res.data || [];
        if (list.length !== 0) {
          list.forEach(i => {
            this.agentIdValue.push(i.id);
          });
        }
      },

      // 拿到运维人员的列表
      async operationFn() {
        let param = {
          pageNum: 1,
          pageSize: 1000
        };
        let res = await this.apis.maintenancer_list(param);
        this.agentArr = []
        if (res) {
          this.tableData = res.rows || [];
          if (this.tableData.length !== 0) {
            this.tableData.forEach(i => {
              let testAgentArr = {
                id: i.id,
                name: i.userName
              };
              this.agentArr.push(testAgentArr);
            });
          }
        }
      },
      // 运维人员绑定站点的确定按钮
      async affirmAgentFn() {
        if (this.agentValue) {
          let params = {
            merId: this.agentValue,
            siteIds: this.agentIdValue || []
          };
          let res = await this.apis.maintenancerBindSite(params);

          this.$message({
            type: res.code == 200 ? "success" : "error",
            message: res.msg
          });
          this.dialogFormVisible = false;
        } else {
          this.$message({
            type: "error",
            message: "请选择运维员"
          });
          return false;
        }
      },

      async elFormSubmit() {
        this.$refs.elForm.$refs.ruleForm.validate(async valid => {
          if (valid) {
            if (!this.formData.id) {
              const res = await this.apis.maintenancer_save({
                phone: this.formData.phone,
                userName: this.formData.userName
              });
            } else {
              const res = await this.apis.maintenancer_updata({
                phone: this.formData.phone,
                userName: this.formData.userName,
                id: this.formData.id
              });
            }
            this.elFormVisible();
            this.init();
          }
        });
      },
      elFormDetail(row) {
        Object.keys(this.formData).forEach(key => {
          this.formData[key] = row[key];
        });
        this.formData.id = row.id;
        this.elFormVisible();
      },
      elFormDetailEditPsw(row) {
        Object.keys(this.formDataEditPsw).forEach(key => {
          this.formDataEditPsw[key] = row[key];
        });
        this.formDataEditPsw.id = row.id;
        this.formDataEditPsw.name = row.name;
        this.formDataEditPsw.phone = row.phone;
        this.formDataEditPsw.password = "";
        this.elFormVisibleEditPsw();
      },
      elFormVisibleEditPsw(tit) {
        if (this.$refs.elFormEditPsw.$refs.ruleFormEditPsw) {
          this.$refs.elFormEditPsw.$refs.ruleFormEditPsw.resetFields();
          this.$data.formDataEditPsw = this.$options.data.call(
            this
          ).formDataEditPsw;
        }
        this.$refs.elFormEditPsw.dialogFormVisible = !this.$refs.elFormEditPsw
          .dialogFormVisible;
        this.$refs.elFormEditPsw.dialogFormTitle = tit
          ? tit
          : this.formDataEditPsw.id
            ? "编辑"
            : "新增";

        if (this.$refs.elFormEditPsw.dialogFormVisible) {
          return new Promise((resolve, reject) => {
            setTimeout(() => {
              resolve();
            }, 2000);
          });
        }
      },
      async elFormSubmitEditPsw() {
        let res = await this.api.putop(this.formDataEditPsw);
        if (res) {
          this.formData.id = "";
          this.elFormVisibleEditPsw();
          this.init();
        }
      },
      //冻结禁用
      elFormDetailActive(row) {
        Object.keys(this.formDataActive).forEach(key => {
          this.formDataActive[key] = row[key];
        });
        this.formDataActive.id = row.id;
        this.elFormVisibleActive();
      },
      elFormVisibleActive(tit) {
        if (this.$refs.elFormActive.$refs.ruleFormActive) {
          this.$refs.elFormActive.$refs.ruleFormActive.resetFields();
          this.$data.formDataActive = this.$options.data.call(
            this
          ).formDataActive;
        }
        this.$refs.elFormActive.dialogFormVisible = !this.$refs.elFormActive
          .dialogFormVisible;
        this.$refs.elFormActive.dialogFormTitle = tit
          ? tit
          : this.formDataActive.id
            ? "编辑"
            : "新增";

        if (this.$refs.elFormActive.dialogFormVisible) {
          return new Promise((resolve, reject) => {
            setTimeout(() => {
              resolve();
            }, 2000);
          });
        }
      },
      async elFormSubmitActive() {
        let res = await this.api.opstate(this.formDataActive);
        if (res) {
          this.elFormVisibleActive();
          this.init();
        }
      }
    }
  };
</script>
<style scoped lang="scss">
  .el-icon-search {
    margin-right: 10px;
  }

  .Tip {
    margin-left: 20px;
  }
</style>